package com.cl.schedule.schedule;

import cn.hutool.cron.CronUtil;
import com.cl.schedule.entity.ScheduleEntity;
import com.cl.schedule.repository.ScheduleRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 添加定时任务注册类，用来增加、删除定时任务。
 *
 * @author 81509
 */
@Slf4j
@Component
public class CronTaskRegistrar<Entity extends ScheduleEntity> implements DisposableBean {

    @Value("${spring.schedule.ksFlowGraph.enable:true}")
    private Boolean enableScheduleFlowGraph;
    private final Map<Integer, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);


    @Autowired
    private BaseStarter baseStarter;
    @Autowired
    private TaskScheduler taskScheduler;
    private final ScheduleRepository scheduleRepository;

    public CronTaskRegistrar(ScheduleRepository<Entity> scheduleRepository) {
        this.scheduleRepository = scheduleRepository;
    }


    public Set<Integer> getSchedulerIds() {
        return scheduledTasks.keySet();
    }

    public String addCronTask(Integer id) {
        if (!enableScheduleFlowGraph) {
            log.info("流程图定时任务已关闭");
            return "流程图定时任务已关闭";
        }
        if (this.scheduledTasks.containsKey(id)) {
            removeCronTask(id);
        }
        Optional<ScheduleEntity> spider = scheduleRepository.findById(id);
        if (spider.isPresent()) {
            spider.get().setIsOpen(1);
            scheduleRepository.save(spider.get());
            ScheduleSchedulingRunnable task = new ScheduleSchedulingRunnable(spider.get(), baseStarter);
            try {
                this.scheduledTasks.put(id, scheduleCronTask(new CronTask(task, spider.get().getCron())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "添加成功";
        }
        return "id不存在";

    }

    public boolean contains(Integer id) {
        return scheduledTasks.containsKey(id);
    }

    public void removeCronTask(Integer id) {
        if (enableScheduleFlowGraph == false) {
            return;
        }
        Optional<ScheduleEntity> spider = scheduleRepository.findById(id);
        if (spider.isPresent()) {
            spider.get().setIsOpen(0);
            scheduleRepository.save(spider.get());
        }
        ScheduledTask scheduledTask = this.scheduledTasks.remove(id);
        if (scheduledTask != null) {
            scheduledTask.cancel();
        }

    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }


    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }
}

@Slf4j
@AllArgsConstructor
class ScheduleSchedulingRunnable implements Runnable {

    private final ScheduleEntity scheduleEntity;

    private final BaseStarter baseStarter;

    @Override
    public void run() {
        baseStarter.start(scheduleEntity);
    }
}
